import java.util.LinkedList;
import java.util.Queue;

public class LC_117 {
    public LC_116.Node connect(LC_116.Node root) {
        Queue<LC_116.Node> que = new LinkedList<>();
        int size = 1;
        if(root == null){
            return root;
        }
        que.offer(root);
        while(!que.isEmpty()){
            int len = size;
            size = 0;
            while(len != 0){
                len--;
                LC_116.Node node = que.poll();
                if(len != 0){
                    node.next = que.peek();
                }else{
                    node.next = null;
                }
                if(node.left != null){
                    size++;
                    que.offer(node.left);
                }
                if(node.right != null){
                    size++;
                    que.offer(node.right);
                }
            }

        }
        return root;
    }
}
